本篇同步發布於Blog: [解題] LeetCode - 739 Daily Temperatures
LeetCode
455 - Assign Cookies
https://leetcode.com/problems/assign-cookies/
輸入一個陣列g,代表小孩對於餅乾的需求度;另一個陣列s,代表餅乾提供的需求度,求這些餅乾最多能滿足幾位小朋友。
比如範例輸入的g = [1, 2, 3], s = [1, 1],只有1個餅乾能滿足需求度為1的小孩,所以答案為1。
使用貪婪法,將g和s都由小到大排序,每次都從最小需求度的小孩和餅乾開始比對,如果目前小孩的需求度無法滿足,就挑下一個餅乾。最終能計算有幾位小朋友得到餅乾。
難度為Easy
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
int child = 0;
int cookie = 0;
while(child < g.size() && cookie < s.size()){
if(g[child] <= s[cookie]){
child++;
}
cookie++;
}
return child;
}
};
int main()
{
vector<int> g{1,2,3};
vector<int> s{1,2};
Solution sol;
int ans = sol.findContentChildren(g, s);
cout << ans << endl;
return 0;
}
using System;
namespace LeetCode455
{
public class Solution {
public int FindContentChildren(int[] g, int[] s) {
Array.Sort(g);
Array.Sort(s);
int child = 0;
int cookie = 0;
while(child < g.Length && cookie < s.Length){
if(g[child] <= s[cookie]){
child++;
}
cookie++;
}
return child;
}
}
class Program
{
static void Main(string[] args)
{
int[] g = new int[] {1, 2};
int[] s = new int[] {1, 2, 3};
Console.WriteLine(new Solution().FindContentChildren(g, s));
Console.Read();
}
}
}
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%2B%2B/400-499/455.cpp
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%23/400-499/455.cs